<template>
  <div id="app">
    <h1>Vue 3 WebSocket Chat</h1>

    <div v-if="!isConnected">Connecting...</div>
    <div v-else>Connected</div>

    <div>
      <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="Type a message..." />
      <button @click="sendMessage">Send</button>
    </div>

    <div>
      <h2>Messages</h2>
      <ul>
        <li v-for="(msg, index) in messages" :key="index">{{ msg.content }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useWebSocket } from '@/websocket';

export default {
  name: 'App',
  setup() {
    const { messages, isConnected, connect, sendMessage } = useWebSocket();
    const newMessage = ref('');

    onMounted(() => {
      connect(); // 初始化 WebSocket 连接
    });

    const sendMessageHandler = () => {
      if (newMessage.value.trim() !== '') {
        sendMessage(newMessage.value); // 发送消息
        newMessage.value = ''; // 清空输入框
      }
    };

    return {
      messages,
      isConnected,
      newMessage,
      sendMessage: sendMessageHandler
    };
  }
};
</script>

<style scoped>
/* 添加样式 */
</style>
